﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
using Sunboxsoft.ASMS.Client.Domain;

namespace Sunboxsoft.ASMS.Client.UI.Create
{
    public partial class CreateOtherStockIncreaseBillView : UserControl, IView
    {
        #region Property
        /// <summary>
        /// 选择入库商品列表
        /// </summary>
        List<WebRef.EStockIncreaseBillItem> list = new List<WebRef.EStockIncreaseBillItem>();
        Promise _promise = new Promise();
        #endregion

        public CreateOtherStockIncreaseBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlLookUpVWarehouse, "入库仓库"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtRemark, "入库备注", true));
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", btnSave_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", btnCancel_Click));
        }

        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                ctlLookUpVWarehouse.BindEWarehouse(_promise, null, true);
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    repositoryItemLookUpEditMode.BindIntCodeTextItem(Domain.Constant.SalesModes.Enumerate());
                    _promise.Resolve();
                }));
            })
            .Run();
        }

        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs != null && args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.View is Pickers.MaterialPicker)
                {
                    WebRef.VMaterial vMaterial = args.ClosedArgs.Data as WebRef.VMaterial;
                    if (vMaterial != null)
                    {
                        WebRef.EStockIncreaseBillItem item = new WebRef.EStockIncreaseBillItem(
                            vMaterial.Id, vMaterial.Code, vMaterial.Name);
                        item.Count = 1;
                        item.Cost = vMaterial.Cost;
                        item.SalesMode = 0;
                        if (list.Exists((WebRef.EStockIncreaseBillItem s) => s.MaterialId == item.MaterialId ? true : false))
                        {
                            UIContext.Current.ViewManager.ShowWarning("此商品已添加过，不能重复添加！");
                        }
                        else
                        {
                            list.Add(item);
                            this.GCData.DataSource = null;
                            this.GCData.DataSource = list;
                        }
                    }
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("创建其他入库单");
        }
        #endregion

        #region Method
        /// <summary>
        /// 数据检查
        /// </summary>
        private bool ValidateData()
        {
            string strMess = null;
            if (!ValidationManager.Validate(this, out strMess))
            {
                UIContext.Current.ViewManager.ShowWarning(strMess);
                return false;
            }
            if (list.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择入库商品！");
                return false;
            }
            else if (GetListItem() == null)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取入库商品列表
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EStockIncreaseBillItem> GetListItem()
        {
            List<WebRef.EStockIncreaseBillItem> listIncreaseItem = this.GVData.DataSource as List<WebRef.EStockIncreaseBillItem>;
            if (listIncreaseItem != null)
            {
                for (int i = 0; i < listIncreaseItem.Count; i++)
                {
                    if (listIncreaseItem[i].Count <= 0)
                    {
                        UIContext.Current.ViewManager.ShowWarning("入库数量应为大于0的正整数！");
                        return null;
                    }
                    if (listIncreaseItem[i].SalesMode == 0)
                    {
                        UIContext.Current.ViewManager.ShowWarning("请选择模式！");
                        return null;
                    }
                }
            }
            return listIncreaseItem;
        }
        /// <summary>
        /// 创建入库单
        /// </summary>
        private void CreateStockIncreaseBill()
        {
            WebRef.EStockIncreaseBill bill = new WebRef.EStockIncreaseBill();
            bill.WarehouseId = this.ctlLookUpVWarehouse.GetSelectedValue<WebRef.VWarehouse>().Id;
            bill.Type = Domain.Constant.StockChangeTypes.IncreaseOther;
            WebRef.EStockIncreaseBillItem[] servies = GetListItem().ToArray<WebRef.EStockIncreaseBillItem>();
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateStockIncreaseBill(bill, servies);
                this.BeginInvoke(new Action<ServiceResult>((p) =>
                {
                    this.HideMask();
                    if (p.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                    }
                }), result);
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        private void btnSave_Click(object obj1, object obj2)
        {
            if (ValidateData())
            {
                CreateStockIncreaseBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        private void btnCancel_Click(object obj1, object obj2)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 商品入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddStock_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.MaterialPicker(Constant.CommonStatus.Enabled),
               new PopupViewArgs("选择商品"));
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEditOperate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "移除")
                {
                    WebRef.EStockIncreaseBillItem model = this.GVData.GetRow(GVData.FocusedRowHandle) as WebRef.EStockIncreaseBillItem;
                    list.Remove(model);
                    if (list.Count == 0)
                    {
                        this.GCData.DataSource = null;
                    }
                    else
                    {
                        this.GCData.DataSource = null;
                        this.GCData.DataSource = list;
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 计算总成本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVData_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.GVData.FocusedColumn == e.Column)
            {
                if (e.Column.FieldName == "Count")
                {
                    WebRef.EStockIncreaseBillItem model = this.GVData.GetRow(e.Column.View.FocusedRowHandle) as WebRef.EStockIncreaseBillItem;
                    this.GVData.SetRowCellValue(e.Column.View.FocusedRowHandle, "Amount", model.Amount);
                }
            }
        }
        #endregion
    }
}
